import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.ServerChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import server.handler.SslChannelInitializer;

public class NettyServer {

  private static int WORKER_GROUP_SIZE = Runtime.getRuntime().availableProcessors() * 2;

  private static EventLoopGroup bossGroup;
  private static EventLoopGroup workerGroup;

  private static Class<? extends ServerChannel> channelClass;

  public static void main(String[] args) throws Exception {
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.childOption(ChannelOption.TCP_NODELAY,true)
        .childOption(ChannelOption.SO_KEEPALIVE,true)
        .childOption(ChannelOption.SO_REUSEADDR,true)
        .childOption(ChannelOption.ALLOCATOR,new PooledByteBufAllocator(false))
        .childOption(ChannelOption.SO_RCVBUF,1048576)
        .childOption(ChannelOption.SO_SNDBUF,1048576);

    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    channelClass = NioServerSocketChannel.class;
    serverBootstrap.group(bossGroup,workerGroup);
    serverBootstrap.channel(channelClass);

    //ssl 代码
    KeyManagerFactory keyManagerFactory = null;
    KeyStore keyStore = KeyStore.getInstance("JKS");
    //加载私钥
    keyStore.load(new FileInputStream("D:/sChat.jks"),"sNetty".toCharArray());
    keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    keyManagerFactory.init(keyStore,"sNetty".toCharArray());

    SslContext sslContext = SslContextBuilder.forServer(keyManagerFactory).build();
    serverBootstrap.childHandler(new SslChannelInitializer(sslContext));

    ChannelFuture future = serverBootstrap.bind(9912).sync();
    future.channel().closeFuture().sync();
  }

}
